package me.firstapp.bts.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import me.firstapp.bts.OpenApiUtils;
import me.firstapp.bts.service.MemberJobService;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.service.weixin.member.MemberService;

@Service
public class MemberJobServiceImpl implements MemberJobService {

	private static Logger logger = LoggerFactory.getLogger(MemberJobServiceImpl.class);

	@Autowired
	private MemberService memberService;

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public void setFansCounts() {
		logger.info("同步粉丝数量开始...");
		long start = System.currentTimeMillis();
		try {
			for (int pageNo = 1; pageNo < 1000000; pageNo++) {
				List<Member> members = memberService.findMembersPage(pageNo, 100);
				if (null == members || members.isEmpty()) {
					break;
				}
				logger.info("待同步的用户数为：" + members.size());
				for (Member member : members) {
					Long counts = memberService.findTotalFansCounts(member.getOpenId());
					member.setFansCounts(null == counts ? 0L : counts);
					memberService.executeUpdateMember(member);
				}
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("同步粉丝数量时遇到错误,错误码：" + e.getCode() + "，错误信息：" + e.getMessage(), e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("同步粉丝数量时遇到错误", e);
		}
		logger.info("同步粉丝数量结束...耗时:" + (System.currentTimeMillis() - start));
	}

	@Override
	public void checkExpire() {
		logger.info("检查服务是否过期开始...");
		long start = System.currentTimeMillis();
		try {
			List<Integer> levelList = new ArrayList<>();
			levelList.add(Member.VIP_LEVEL_BASE);
			levelList.add(Member.VIP_LEVEL_HIGHT);
			for (int pageNo = 1; pageNo < 1000000; pageNo++) {
				List<Member> members = memberService.findMembersPage(pageNo, 100, levelList);
				if (null == members || members.isEmpty()) {
					break;
				}
				logger.info("待检查的用户数为:" + members.size());
				for (Member member : members) {
					if (Member.VIP_LEVEL_FANS != member.getVipLevel()) {
						try {
							int days = DateUtils.daysBetween(new Date(), member.getExpireDate());
							logger.info("用户【" + member.getCardNo() + "】剩余服务天数为：" + days);
							if (days <= 0) {
								int oldLevel = member.getVipLevel();
								member.setVipLevel(Member.VIP_LEVEL_FANS);
								member.setExpireDate(
										DateUtils.getDateFromDateStr("2117-09-09 23:59:59", "yyyy-MM-dd HH:mm:ss"));
								memberService.executeUpdateMember(member);
								// 发送等级变更通知
								int newLevel = member.getVipLevel();
								OpenApiUtils.sendLevelChangeMsg(restTemplate, member.getOpenId(), oldLevel, newLevel);
							} else if (days <= 3) {
								// 发送到期通知
								OpenApiUtils.sendLevelExpireMsg(restTemplate, member.getOpenId());
							}

						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("检查服务是否过期时遇到错误,错误码：" + e.getCode() + "，错误信息：" + e.getMessage(), e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("检查服务是否过期时遇到错误", e);
		}
		logger.info("检查服务是否过期结束...耗时:" + (System.currentTimeMillis() - start));
	}

}
